package IK;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;
import java.io.IOException;
import java.io.StringReader;

class MyMapper extends Mapper<LongWritable,Text,Text,LongWritable>{
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        //使用分词器将一行数据进行分词
        StringReader sr = new StringReader(value.toString());
        //使用IK分词器进行分词
        IKSegmenter ik = new IKSegmenter(sr, true);
        Lexeme lexeme = null;
        while ((lexeme = ik.next())!=null){
            String word = lexeme.getLexemeText();
            if ("朱元璋".equals(word)||"陈友谅".equals(word)||"常胜春".equals(word)){
                context.write(new Text(word),new LongWritable(1L));
            }
        }
    }
}
class MyReducer extends Reducer<Text,LongWritable,Text,LongWritable>{
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        Long sum = 0L;
        for (LongWritable value : values) {
            long l = value.get();
            sum += l;
        }
        context.write(key,new LongWritable(sum));
    }
}
public class MCNXSDemo {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        //获取hadoop集群的环境配置
        Configuration conf = new Configuration();
        //创建一个任务
        Job job = Job.getInstance(conf);
        //设置reduce数量
        job.setNumReduceTasks(1);
        //设置任务名称
        job.setJobName("统计陈友谅、朱元璋、常胜春的个数");
        //设置运行主类
        job.setJarByClass(MCNXSDemo.class);
        //设置map类
        job.setMapperClass(MyMapper.class);
        //设置reducer类
        job.setReducerClass(MyReducer.class);
        //设置map任务输出类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);
        //设置reduce任务输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);
        //设置读取路径
        FileInputFormat.setInputPaths(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));
        job.waitForCompletion(true);
    }
}
